package simplejson

import (
	"reflect"
)

type InterfaceArr []interface{}

//由于切片是值类型，故用_ArrayJson类型存储数组，序列化时需要转换
type _ArrayJson struct {
	InterfaceArr
}

func newArrayJson() *_ArrayJson {
	return &_ArrayJson{
		InterfaceArr: make([]interface{}, 0),
	}
}

func (j *_Json) GetInterfaceByIndex(idx int) interface{} {
	switch j.data.(type) {
	case []interface{}:
		return j.data.([]interface{})[idx]
	case InterfaceArr:
		return j.data.(InterfaceArr)[idx]
	case *_ArrayJson:
		return j.data.(*_ArrayJson).InterfaceArr[idx]
	default:
		return nil
	}
}
func (j *_Json) ArrayLen() int {
	switch j.data.(type) {
	case []interface{}:
		return len(j.data.([]interface{}))
	case InterfaceArr:
		return len(j.data.(InterfaceArr))
	case *_ArrayJson:
		return len(j.data.(*_ArrayJson).InterfaceArr)
	default:
		return 0
	}
}

func (j *_Json) GetByIndex(idx int) Json {
	return &_Json{data: j.GetInterfaceByIndex(idx)}
}
func (j *_Json) Add(v interface{}) {
	m, ok := v.(*_Json)
	var arrObj *_ArrayJson = nil

	a, isArjs := j.data.(*_ArrayJson)
	if isArjs {
		arrObj = a
	} else {
		arrObj = &_ArrayJson{
			InterfaceArr: j.data.([]interface{}),
		}
	}

	if ok {
		//j.data = append(j.data.([]interface{}), m.data)
		arrObj.InterfaceArr = append(arrObj.InterfaceArr, m.data)
	} else {
		//j.data = append(j.data.([]interface{}), v)
		arrObj.InterfaceArr = append(arrObj.InterfaceArr, v)
	}
}
func (j *_Json) NewObjectAdd() Json {
	nj := New()
	j.Add(nj)
	return nj
}
func (j *_Json) NewArrayAdd() Json {
	nj := NewArray()
	j.Add(nj)
	return nj
}
func (j *_Json) IsArray() bool {
	switch j.data.(type) {
	case []interface{}:
		return true
	case InterfaceArr:
		return true
	case *_ArrayJson:
		return true
	default:
		t := reflect.TypeOf(j.data)
		tname := t.String()
		_ = tname
		return false

	}
	return false
}
func (j *_Json) GetBoolByIndex(idx int) bool {
	return asBool(j.GetInterfaceByIndex(idx))
}
func (j *_Json) GetIntByIndex(idx int) int {
	return asInt(j.GetInterfaceByIndex(idx))
}
func (j *_Json) GetUintByIndex(idx int) uint {
	return asUint(j.GetInterfaceByIndex(idx))
}
func (j *_Json) GetInt64ByIndex(idx int) int64 {
	return asInt64(j.GetInterfaceByIndex(idx))
}
func (j *_Json) GetUint64ByIndex(idx int) uint64 {
	return asUint64(j.GetInterfaceByIndex(idx))
}
func (j *_Json) GetFloat32ByIndex(idx int) float32 {
	return asFloat32(j.GetInterfaceByIndex(idx))
}
func (j *_Json) GetFloat64ByIndex(idx int) float64 {
	return asFloat64(j.GetInterfaceByIndex(idx))
}
func (j *_Json) GetStringByIndex(idx int) string {
	return asString(j.GetInterfaceByIndex(idx))
}
